package test.study.concurrent.thread._8_mdc;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MdcCallable<V> implements Callable<V> {

    private Callable<V> task;

    private final Map<String, String> contextMap;

    public MdcCallable(Callable<V> task) {
        this.task = task;
        this.contextMap = MDC.getCopyOfContextMap();
    }

    @Override
    public V call() throws Exception {
        V value;
        MDC.setContextMap(contextMap);
        try {
            value = task.call();
        } finally {
            MDC.clear();
        }
        return value;
    }

    public static void main(String[] args) throws Exception {

        ForkJoinPool pool = new ForkJoinPool(100);

        MDC.put("trace_id", "666666");
        log.info(">>>>>> main thread");
        String result = pool.submit(new MdcCallable<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("other thread");
                log.info("other thread");
                log.info("other thread");
                return "aaaaaaaaaaa";
            }
        })).get();

        ThreadUtil.sleep(3, TimeUnit.SECONDS);
    }
}
